package zut.cs.liziflower.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import zut.cs.liziflower.entity.Result;
import zut.cs.liziflower.service.impl.ConsumerServiceImpl;
import zut.cs.liziflower.utils.QiniuUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 许文科
 * @Date 2022/5/20 9:45
 */
@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Resource
    private QiniuUtil qiniuUtil;
    @Resource
    private ConsumerServiceImpl consumerService;

    /**
     * 头像文件上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/images")
    public Result<?> uploadImages(@RequestParam("userid") Integer userid, MultipartFile file) throws Exception {
        String url;
        int flag;//更新成功标志
        if (file == null) {
            return Result.error("405", "上传错误", null);
        }
        try {
            byte[] bytes = file.getBytes();//将文件转化为 byte[] 格式
            String name = UUID.randomUUID().toString().replace("-", "");//更改后的文件名
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());//获取文件后缀
            String ur = name + "." + ext;
            url = qiniuUtil.uploadBybyte(bytes, ur);

            //将url更新为该用户的头像
            flag = consumerService.updateAvator(userid, url);

            if (flag == 1) {
                return Result.success(url);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("405", "更新失败", null);
    }
}
